<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/2/16 14:18
 * Remark:
 */

namespace App\Http\Middleware\Auth;

use App\Consts\AuthConsts\AuthConsts;
use App\Consts\RequestConsts\RequestMethodConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use Closure;
use Illuminate\Http\Exceptions\HttpResponseException;

class BulkyAuthMiddleware
{
    /**
     * @param $path
     */
    private function methodGetRoute($path){
        $data = TokenFuc::getCurrentStaffInfo();
        $userAuth = array_column($data['userAuth'],'auth_key','auth_code');

        if(substr_count($path,"/")>=2){
            $path = explode('/',$path);
            $path = $path[0]."/".$path[1];
        }
        switch ($path){
            case "api/clientList":
            case "api/client":
                if(!isset($userAuth[AuthConsts::SELECT_CLIENT_AUTH]) || $userAuth[AuthConsts::SELECT_CLIENT_AUTH] == 0){
                    throw new HttpResponseException( ResponseFunc::returnJson(
                        'error',
                        null,
                        "非法请求",
                        ResponseStatusConsts::UNAUTHORIZED_401_RESPONSE_STATUS
                    ));
                }
                break;
        }
    }

    private function methodPostRoute($path){
        $data = TokenFuc::getCurrentStaffInfo();
        $userAuth = array_column($data['userAuth'],'auth_key','auth_code');
        if(substr_count($path,"/")>=2){
            $path = explode('/',$path);
            $path = $path[0]."/".$path[1];
        }
        switch ($path){
            case "api/client":
            case "api/enterprise":
                if(
                    !isset($userAuth[AuthConsts::OP_CLIENT_AUTH]) ||
                    $userAuth[AuthConsts::OP_CLIENT_AUTH] == 0 ||
                    !(bool)($userAuth[AuthConsts::OP_CLIENT_AUTH] & AuthConsts::AUTH_ADD)
                ){
                    throw new HttpResponseException( ResponseFunc::returnJson(
                        'error',
                        null,
                        "非法请求",
                        ResponseStatusConsts::UNAUTHORIZED_401_RESPONSE_STATUS
                    ));
                }
                break;
        }
    }


    public function handle($request, Closure $next)
    {
        // 分流
        $path = $request->path();
        $method = strtolower($request->method());
        switch ($method){
            case RequestMethodConsts::GET_METHOD:
                $this->methodGetRoute($path);
            break;
            case RequestMethodConsts::POST_METHOD:
                $this->methodPostRoute($path);
            break;
        }
        return $next($request);
    }
}